<?php

namespace App\Services\Com;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Vod\Vod;
use FFMpeg\Coordinate\Dimension;
use FFMpeg\Coordinate\TimeCode;
use FFMpeg\FFMpeg;
use App\Models\Common\City;
use Illuminate\Filesystem\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Storage;
use OSS\OssClient;

class UtilService
{
    /**
     * 城市转换出市id
     * 处理直辖市，和传区id
     */
    public static function getCityId(string $place_city_code = '')
    {
        //如果此城市为父类，下面有数据
        $city_arr = City::getCityByParentId($place_city_code);

        //没有数据就是区，查他的父级市，找全部父级为此id的
        if(empty($city_arr)){ 
            $place_city_code_arr_2 = City::getCityById($place_city_code);            
            $city_arr = City::getCityByParentId($place_city_code_arr_2['parent_id'] ?? '');
        }

        if(!empty($city_arr)){
            foreach ($city_arr as $c_key => $c_value) {
                $cidy_arr[] = $c_value['id'];
            }
            $cidy_arr[] = (int)$place_city_code;
            if(isset($place_city_code_arr_2['parent_id'])){
                $cidy_arr[] = $place_city_code_arr_2['parent_id'];
            }
            $city_ids = $cidy_arr;
        }else{
            $city_ids[] = -1;//不显示数据
        }

        return $city_ids;
    }

    /**
     * 图片缩略图
     * @param  string  $ori_url 图片原尺寸
     *
     * @return string coverURL $ori_url.'?x-oss-process=image/resize,w_300/quality,q_90'
     *
     *宽度固定，高度自适应 image/auto-orient,1/resize,m_lfit,w_200/quality,q_100
     *高度固定，宽度自适应 image/auto-orient,1/resize,m_lfit,h_200/quality,q_100
     *固定宽高，按长边缩放 image/auto-orient,1/resize,m_lfit,w_200,h_200/quality,q_100
     *固定宽高，按短边缩放 image/auto-orient,1/resize,m_mfit,w_200,h_200/quality,q_100
     *固定宽高，缩略填充 image/auto-orient,1/resize,m_pad,w_200,h_200/quality,q_100
     *固定宽高，居中裁剪 image/auto-orient,1/resize,m_fill,w_200,h_200/quality,q_100
     *强制宽高 image/auto-orient,1/resize,m_fixed,w_200,h_200/quality,q_100
     *
     *
     *
     *
     */
    public static function coverURL(string $ori_url = '')
    {
        return $ori_url.'?x-oss-process=image/resize,w_600/quality,q_100';
    }
    
    /**
     * 根据经纬度计算 距离批量
     * origins
     * 出发点
     * 支持100个坐标对，坐标对见用“| ”分隔；经度和纬度用","分隔
     * destination
     * 目的地
     * 反过来计算，当前人对这些坐标的距离
     * https://restapi.amap.com/v3/distance?origins=116.481028,39.989643|114.481028,39.989643|115.481028,39.989643&destination=114.465302,40.004717&output=xml&key=<用户的key>
     * @param  string  $user_l1 = '' 起始坐标
     * @param  string  $user_l2 = '' 起始坐标
     * @param  string  $s_l1 = ''    结束坐标
     * @param  string  $s_l2 = ''    结束坐标
     * @return string 米: null || 123
     */
    public static function batchDistance($origins = '', $s_l1 = '', $s_l2 = '')
    {
        $http = new \GuzzleHttp\Client;
        $url = env('A_MAP_API_URL').'/distance?origins='.$origins.'&destination='.$s_l1.','.$s_l2.'&type=0&output=json&key='.env('A_MAP_API_WEB_KEY');
        $response = $http->get($url);
        $result = json_decode((string)$response->getBody(), true);
        $distance = null;
        if(isset($result['results'][0]['distance'])){
            $distance = $result['results'][0]['distance'];
        }
        return $distance;
    }

    /**
     * 根据经纬度计算此坐标的位置
     * $param['longitude'].','.$param['latitude']
     * curl -i 'https://restapi.amap.com/v3/geocode/regeo?output=json&location=114.017744,22.537611&key=7302aeada6abf860045f8ca4c05d6c31&radius=10&extensions=false'
     * @param  string  $location 坐标 114.017735,22.537715
        {"status":"1","regeocode":{"addressComponent":{"city":"深圳市","province":"广东省","adcode":"440304","district":"福田区","towncode":"440304006000","streetNumber":{"number":[],"direction":[],"distance":[],"street":[]},"country":"中国","township":"香蜜湖街道","businessAreas":[[]],"building":{"name":[],"type":[]},"neighborhood":{"name":[],"type":[]},"citycode":"0755"},"formatted_address":"广东省深圳市福田区香蜜湖街道一家福(香蜜湖店)鑫竹苑生活广场"},"info":"OK","infocode":"10000"}

     * @return string 米: null || 123
     */
    public static function getRegeo($location= '', $return_all = 'address')
    {
        $http = new \GuzzleHttp\Client;
        $url = env('A_MAP_API_URL').'/geocode/regeo?output=json&location='.$location.'&key='.env('A_MAP_API_WEB_KEY').'&radius=10&extensions=false';
        
        $response = $http->get($url);
        $result = json_decode((string)$response->getBody(), true);
        $distance = null;
        if($return_all == 'address'){
            if(isset($result['regeocode']['formatted_address'])){
                $distance = $result['regeocode']['formatted_address'];
            }
        }else{
            $distance = $result;
        }
        
        return $distance;
    }

    /**
     * 根据经纬度计算 距离
     * @param  string  $user_l1 = '' 起始坐标
     * @param  string  $user_l2 = '' 起始坐标
     * @param  string  $s_l1 = ''    结束坐标
     * @param  string  $s_l2 = ''    结束坐标
     * @return string 米: null || 123
     */
    public static function distance($user_l1 = '', $user_l2 = '', $s_l1 = '', $s_l2 = '')
    {
        $http = new \GuzzleHttp\Client;
        $url = env('A_MAP_API_URL').'/distance?origins='.$user_l1.','.$user_l2.'&destination='.$s_l1.','.$s_l2.'&type=0&output=json&key='.env('A_MAP_API_WEB_KEY');
        $response = $http->get($url);
        $result = json_decode((string)$response->getBody(), true);
        $distance = null;
        if(isset($result['results'][0]['distance'])){
            $distance = $result['results'][0]['distance'];
        }
        return $distance;
    }

    /**
     * 用户uuid生成环信im用户名
     * 规则 md5($uuid)
     * @param  string  $uuid  用户uuid
     *
     * @return string 环信用户名
     */
    public static function memberUuidToImAccount(string $uuid = '')
    {
        if(empty($uuid)){
            return '';
        }
        return md5($uuid);
    }

    /**
     * 用户uuid生成环信im用户的密码
     * 规则 md5($param['uuid'].'_abc123')
     * @param  string  $uuid  用户uuid
     *
     * @return string 环信用户密码
     */
    public static function memberUuidToImPassword(string $uuid = '')
    {
        return md5($uuid.'_abc123');
    }


    /**
     * 移动HTML的临时图片文件到指定目录
     *
     * @param  string  $html    HTML
     * @param  string  $newDir  目录路径（相对）
     *
     * @return string HTML
     */
    public static function moveHtmlTmpImagesToDir(string $html, string $newDir)
    {
        $preg = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
        preg_match_all($preg, $html, $files);

        if ($files && isset($files[1]) && count($files[1]))
        {
            foreach ($files[1] as $file)
            {
                $file = trim($file, '/');
                if (file_exists(public_path($file)) && 0 === stripos($file, 'uploadfiles/tmp'))
                {
                    if (!file_exists(public_path($newDir)))
                    {
                        @mkdir(public_path($newDir), 0777, true);
                    }
                    $newFile = trim($newDir, '/').'/'.basename($file);
                    File::move(public_path($file), public_path($newFile));
                    $html = str_replace($file, $newFile, $html);
                }
            }
        }

        return $html;
    }

    /**
     * 移动文件到目录
     *
     * @param  string    $file
     * @param  string    $newFile
     * @param  int|null  $width
     * @param  int|null  $height
     *
     * @return string
     */
    public static function moveTmpFileToNewFile(string $file, string $newFile)
    {
        if (!is_string($file) || empty($file))
        {
            return null;
        }

        $tmp  = 'uploadfiles/tmp';
        $file = trim($file, '/');

        if (-1 === stripos($file, $tmp))
        {
            return $file;
        }

        $file     = substr($file, stripos($file, $tmp));
        $pathinfo = pathinfo(public_path($newFile));

        if (!isset($pathinfo['extension']))
        {
            $newFile = trim($newFile, '/') . '/' . basename($newFile);
        }

        $dir = dirname(public_path($newFile));

        if (!file_exists($dir))
        {
            @mkdir($dir, 0755, true);
        }

        if (file_exists(public_path($file)))
        {
            File::move(public_path($file), public_path($newFile));
        }

        return $newFile;
    }

    /**
     * 移动文件到目录
     *
     * @param  string  $file
     * @param  string  $newFile
     *
     * @return string
     */
    public static function moveTmpFileToDir(string $file, string $newFile)
    {
        $file = trim($file, '/');
        $file = '/'.strstr($file, 'uploadfiles');


        if (false === stripos($file, 'uploadfiles/tmp'))
        {
            return $file;
        }

        $newFile = trim($newFile, '/');

        if (false === stripos($newFile, 'uploadfiles'))
        {
            $newFile = 'uploadfiles/' . $newFile;
        }

        if (!is_dir($newFile))
        {
            mkdir(public_path($newFile), 0777, true);
        }

        $newFile = trim($newFile, '/') . '/' . basename($file);

        if (file_exists(public_path($file)))
        {
            File::move(public_path($file), public_path($newFile));
        }

        return $newFile;
    }

    public static function videoToGif(string $file)
    {
        $file = trim($file, '/');
        $file = '/'.strstr($file, 'uploadfiles');

        $newFile = pathinfo($file, PATHINFO_DIRNAME) .'/'. pathinfo($file, PATHINFO_FILENAME).'.gif';

        $ffmpeg = FFMpeg::create(array(
            'ffmpeg.binaries' => 'ffmpeg',
            'ffprobe.binaries' => 'ffprobe',
            'timeout' => 3600,
            'ffmpeg.threads' => 12,
        ));

        $video = $ffmpeg->open(public_path($file));
        $video
            ->gif(TimeCode::fromSeconds(0), new Dimension(200, 200), 3)
            ->save(public_path($newFile));

        return $newFile;
    }
    /**
     * 生成16位随机数
     *
     * @return string
     */
    public static function no()
    {
        return (rand(10000000, 99999999));
    }

    /**
     * getRandChar 获取随机字符串
     *
     * @param  int  $length
     *
     * @return null|string
     */
    static public function getRandChar($length = 32, $strPol='')
    {
        $str    = null;
        if(empty($strPol))  $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";

        $newStr = str_shuffle($strPol);
        $max    = strlen($strPol) - 1;
        for ($i = 0; $i < $length; $i++)
        {
            $str .= $newStr[mt_rand(0, $max)];
        }
        return $str;
    }

    /**
     * 生成唯一数字ID
     *
     * @return string
     */
    public static function uniqid()
    {
        return (date('YmdHis').crc32(md5(uniqid(mt_rand(), true))));
    }

    /**
     * 当前路由前缀名
     *
     * @param  null  $prefix
     *
     * @return string
     */
    public static function prefix($prefix = null)
    {
        if ($prefix)
        {
            if (is_array($prefix))
            {
                return in_array(strtoupper(Request::route()->getPrefix()), array_map(function ($str)
                {
                    return strtoupper($str);
                }, $prefix));
            }
            else
            {
                return (strtoupper(Request::route()->getPrefix()) === strtoupper($prefix));
            }
        }
        else
        {
            return strtoupper(Request::route()->getPrefix());
        }
    }

    /**
     *  下载文件
     *
     * @param $url
     *
     * @return bool|string
     */
    public static function download($url, $file)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_ENCODING, ""); //加速 这个地方留空就可以了
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);

        if (!file_exists(dirname($file)))
        {
            @mkdir(dirname($file), 0755, true);
        }

        file_put_contents($file, $output);

        return $file;
    }

    /**
     *  下载微信图片
     *
     * @param $url
     *
     * @return bool|string
     */
    public static function downWxImage($image_url, $newDir = ''){
        try{
            // 生成文件名
            $fullName = UtilService::getFullNameByExt('jpg');

            $path = "uploadfiles/" . (empty($newDir) ? '' : $newDir . '/') . $fullName;
            if (!file_exists(public_path($path)))
            {
                @mkdir(dirname(public_path($path)), 0755, true);
            }
            $disk = Storage::disk();
            $result = $disk->put((empty($newDir) ? '' : $newDir . '/') . $fullName, file_get_contents($image_url));
            if(!$result){
                throw new \Exception('上传用户头像失败',1002);
            }
            return $path;
        }catch(\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }

    public static function week()
    {
        $weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        return $weeks[date("w")];
    }

    /** 金额格式化
     *
     * @param       $price    传入金额 单位分
     * @param  int  $decimal  保留小数位数
     *
     * @return float
     */
    public static function priceFormat($price, $decimal = 2)
    {
        return (float) round(((int) $price / 100), $decimal);
    }

    /**
     * 生成唯一字符串
     * @param int $length  生成字符串长度
     * @param array $arr  已有字符串数组集
     * @param String $char 生成条件
     * @return bool|string  返回字符串类型
     */
    public static function str_union_rand(int $length = 4, array $arr = [], String $char = '0123456789'){
        if($length < 0){
            return false;
        }
        $string = '';
        for($i=$length; $i>0; $i--){
            $string .= $char[mt_rand(0, strlen($char) - 1)];
        }

        if(!empty($arr) && in_array($string, $arr)){
            self::str_union_rand($length, $arr, $char);
        }

        return $string;
    }

    //以下为获取ip函数
    public static function getClientIp(){
        $realip = '';
        $unknown = 'unknown ip';
        if (isset($_SERVER)){
            if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                foreach($arr as $ip){
                    $ip = trim($ip);
                    if ($ip != 'unknown'){
                        $realip = $ip;
                        break;
                    }
                }
            }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){
                $realip = $_SERVER['REMOTE_ADDR'];
            }else{
                $realip = $unknown;
            }
        }else{
            if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){
                $realip = getenv("HTTP_CLIENT_IP");
            }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){
                $realip = getenv("REMOTE_ADDR");
            }else{
                $realip = $unknown;
            }
        }
        $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;

        return $realip;
    }

    /**
     * 获取 IP  地理位置
     * 淘宝IP接口
     * @Return: array
     */
    public static function GetIpLookup($ip = '')
    {
        if($ip == ''){
            $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
            $ip=json_decode(file_get_contents($url),true);
            $data = $ip;
        }else{
            $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
            $ip=json_decode(file_get_contents($url));
            if((string)$ip->code=='1'){
                return false;
            }
            $data = isset($ip->data) ? (array)$ip->data : [];
        }

        return json_encode($data);
    }

    //根据上传文件设置文件名
    public static function getFullNameByExt($extension = 'png')
    {
        $timeStmp = date('YmdHis');
        return sprintf('%s%s%d.%s', $timeStmp, md5($timeStmp), mt_rand(1111, 9999), $extension);
    }

    public static function curl_get($url, $headerParam=[]){

        $header = ['Content-Type: application/json', 'Transfer-Encoding: chunked'];

        !empty($headerParam) && $header = array_merge($header, $headerParam);

        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);

        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);

        // 显示错误信息
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);exit;
        }

        curl_close($curl);

        return json_decode($data, true);
    }

    public static function curlPostFile($url , $data=array(), $headerParam=[], $file=null){

        $ch = curl_init();

        $header = ['Content-Type: application/json', 'Transfer-Encoding: chunked'];
        !empty($headerParam) && $header = array_merge($header, $headerParam);


        //上传文件
        if(!empty($file)){
            $file_obj=new \CURLFile($file,'image/jpeg','file');
            $data["{$file['name']}"]=$file_obj;
        }


        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);// 必须为字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER,    $header);// 必须声明请求头
        // 超时设置,以秒为单位
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        $output = curl_exec($ch);

        curl_close($ch);

        return json_decode($output, true);
    }

    public static function curlPost($url , $data=array(), $headerParam=[]){

        $ch = curl_init();

        $header = ['Content-Type: application/json', 'Transfer-Encoding: chunked'];
        !empty($headerParam) && $header = array_merge($header, $headerParam);

//        !empty($headerParam) && dd($header);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));// 必须为字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER,    $header);// 必须声明请求头
        // 超时设置,以秒为单位
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        //执行命令
        $data = curl_exec($ch);

        // 显示错误信息
        if (curl_error($ch)) {
            print "Error: " . curl_error($ch);exit;
        }

        curl_close($ch);

        return json_decode($data, true);


        $output = curl_exec($ch);

        // 显示错误信息
        if (curl_error($curl)) {
            print "Error: " . curl_error($curl);exit;
        }

        curl_close($ch);

        return json_decode($output, true);
    }

    public static function curl_raw_post($url , $data=array(), $headerParam=[]){

        $ch = curl_init();

        $header = ['Content-Type: text/plain'];
        !empty($headerParam) && $header = array_merge($header, $headerParam);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));// 必须为字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER,     $header);// 必须声明请求头

        $output = curl_exec($ch);

        curl_close($ch);

        return json_decode($output, true);
    }

    //返回当前的毫秒时间戳
    public static function msectime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

        return $msectime;
    }

    /**
     * 上传阿里云oss文件
     * @param $object  目标路径（包含文件名）
     * @param $filePath  本地文件全地址
     * @return bool
     * @throws \Exception
     */
    public static  function ossUploadFile($object, $filePath)
    {
        try {
            $ossClient = new OssClient(config('aliyun.aliyunoss.accessKeyId'), config('aliyun.aliyunoss.accessKeySecret'), config('aliyun.aliyunoss.endpoint'));

            $response = $ossClient->uploadFile(config('aliyun.aliyunoss.bucket'), $object, $filePath);
            if (empty($response['oss-request-url'])) throw new \Exception('上传失败');
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return $response['oss-request-url'];
    }

    /**
     * 上传阿里云oss文件
     * @param $object  目标路径（包含文件名）
     * @param $filePath  文件流
     * @return bool
     * @throws \Exception
     */
    public static  function ossUploadObject($object, $obj)
    {
        try {
            $ossClient = new OssClient(config('aliyun.aliyunoss.accessKeyId'), config('aliyun.aliyunoss.accessKeySecret'), config('aliyun.aliyunoss.endpoint'));

            $response = $ossClient->putObject(config('aliyun.aliyunoss.bucket'), $object, $obj);
            if (empty($response['oss-request-url'])) throw new \Exception('上传失败');
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return $response['oss-request-url'];
    }

    /*
     @Author Sea <34422611@qq.com> v1.01
     @Param string $str
     @Param int $start 起始位置 从0开始计数  负数倒转替换
     @Param (int or string) $length 当 $length=string 替换 $key
     @Param (int or string) $key 填充的隐藏的字符 默认 *
     @Param string $charset 可废弃 删除 ($key && $charset = $key) 和 ($charset='utf8') 语句;

     @Param int $split 可拓展
     $split_card = implode(' ',str_split($str_hide,4));  // 分割卡号
     */
    public static function str_hide($str,$start,$length=0,$key='',$charset='utf8'){
        // 使用支持补0，当 $length=string 替换 $key
        if(strlen($length) && gettype($length) != "integer"){
            $key && $charset = $key;
            $key = $length;
            $length = 0;
        }
        $Par = $length?[$start,$length]:[$start]; //array_filter([$start,$length]);
        // use $charset;
        //$e or $e = mb_strlen($str);
        //$Par     = [$start,$length,$charset];
        $rep_str = mb_substr($str,...$Par);
        strlen($key) or $key = '*';
        strlen($key) == 1 && $key = str_pad('',mb_strlen($rep_str),$key);
        $start  = strlen(mb_substr($str,0,$start));
        $count  = strlen($rep_str);
        $result = substr_replace($str,$key,$start,$count);

        return $result;
    }


    //通过视频id获得视频地址
    public static function getVideoUrl($vdo_id){
        try {
            //设置全局客户端
            AlibabaCloud::accessKeyClient(config('aliyun.aliyunvideo.accessKeyId'), config('aliyun.aliyunvideo.accessKeySecret'))
                ->regionId(config('aliyun.aliyunvideo.regionId'))
                ->asDefaultClient();

            $request = Vod::v20170321()->getPlayInfo();

            $result = $request->withVideoId($vdo_id)->debug(false)->request();
            $video_arr = $result->toArray();

            $resultData = [
                'vdo_id' => $vdo_id,
                'coverURL' => $video_arr['VideoBase']['CoverURL'] ?? '',
                'playURL' => $video_arr['PlayInfoList']['PlayInfo'][0]['PlayURL'] ?? '',
            ];
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }

        return $resultData;
    }


    /**
     * 准备工作完毕 开始计算年龄函数
     * @param  $birthday 出生时间 uninx时间戳
     * @param  $time 当前时间
     **/
    public static function getAge($birthday){
        //格式化出生时间年月日
        $byear=date('Y',$birthday);
        $bmonth=date('m',$birthday);
        $bday=date('d',$birthday);

        //格式化当前时间年月日
        $tyear=date('Y');
        $tmonth=date('m');
        $tday=date('d');

        //开始计算年龄
        $age=$tyear-$byear;
        if($bmonth>$tmonth || $bmonth==$tmonth && $bday>$tday){
            $age--;
        }
        return $age;
    }

    //删除oss图片
    public static function deleteOssFile($file){
        $ossClient = new OssClient(config('aliyun.aliyunoss.accessKeyId'), config('aliyun.aliyunoss.accessKeySecret'), config('aliyun.aliyunoss.endpoint'));

        $response = $ossClient->deleteObject('deyao-pharmacy', $file);
    }

}
